# chat/consumers.py
import json
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
from chat.models import WordReplyMap, ChatRecord
from user.models import User
from threading import Thread


class ChatConsumer(WebsocketConsumer):
    def connect(self):
        self.room_name = self.scope["url_route"]["kwargs"]["room_name"]
        self.room_group_name = f"chat_{self.room_name}"

        # Join room group
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name, self.channel_name
        )

        # 进入提醒
        username = self.scope.get('cookies', {}).get('username')
        self.scope['user'] = User.get_by_username(username)
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name, {"type": "chat_message",
                                   "message": f'[{username}]进入房间...'}
        )
        self.accept()
        # 状态修改为在线 TODO
        self.scope['user'].is_activate = True
        self.scope['user'].save()

    def disconnect(self, close_code):
        # Leave room group
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name, self.channel_name
        )

        # 状态修改为离线 TODO
        self.scope['user'].is_activate = False
        self.scope['user'].save()

    # Receive message from WebSocket
    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json["message"]
        chat_target = text_data_json["chat_target"]

        # Send message to room group
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name, {"type": "chat_message", "message": message}
        )

        # TODO 如果聊天对象不在线就自动回复
        tmp_user = User.get_by_username(chat_target)
        ChatRecord.create_record(
            self.scope['user'], tmp_user, message.split(':', 1)[1])

        if not tmp_user.is_active and tmp_user.is_auto_reply:
            def auto_reply(self, chat_target, message):
                # 首先搜索词库表
                reply = WordReplyMap.match(message)
                # 如果没有就再调用自动回复接口
                reply = reply or User.auto_reply(message)
                async_to_sync(self.channel_layer.group_send)(
                    self.room_group_name, {
                        "type": "chat_message", "message": f'{chat_target}:{reply}[自动回复].'}
                )
                ChatRecord.create_record(tmp_user, self.scope['user'], reply)

            th = Thread(target=auto_reply, args=(
                self, chat_target, message))
            th.start()

        print(f'当前发言的是：{self.scope["user"]}，聊天对象是：{chat_target}')

    # Receive message from room group
    def chat_message(self, event):
        message = event["message"]

        # Send message to WebSocket
        self.send(text_data=json.dumps({"message": message}))
